//这个文件，专门处理用户登陆注册
const express = require('express')
const bcryptjs = require('bcryptjs')
const router = express.Router()
const UsersModel = require('../models/users')

// 处理注册  username ， password （必填）账号不可重复注册
router.post('/register', async (req, res) => {
    let username = req.body.username;
    let password = req.body.password
    password = await bcryptjs.hash(password, 12)

    let message = await UsersModel.find();
    message.forEach(item => {
        if (item.username == username) {
            res.send(({
                code: -1,
                mas: '账号重复'
            }))
            return
        }
    })
    const user = new UsersModel({
        username,
        password
    });
    user.save()
    res.send(JSON.stringify({
        code: 0,
        mas: '用户注册成功'
    }))
})
// 处理登陆  
router.post('/login', async (req, res) => {
    let username = req.body.username;
    let password = req.body.password;

    const user = await UsersModel.findOne({ username })
    let isok = false;
    if (user) {
        isok = await bcryptjs.compare(password, user.password)
    }
    if (isok) {
        req.session.userInfo = {
            userId: user._id,
            username: user.username,
            nickname: user.nickname
        }
        res.send({
            code: 0,
            mas: '登陆成功'
        })
    } else {
        res.send({
            code: -1,
            mas: '用户名或密码不正确'
        })
    }
})

module.exports = router;
